<template>
  <div>
    <!-- 文章列表 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
    <van-list v-model="loading" :finished="finished" finished-text="没有更多了"  @load="onLoad" :immediate-check="false" offset="40">
    <Article-item v-for="(item,index) in articlesList" :key="item.art_id + index" :articlesObj="item"></Article-item>
   </van-list>
   </van-pull-refresh>
  </div>
</template>

<script>
import ArticleItem from '@/components/ArticleItem'
import { getArticleListAPI } from '@/api'
import formatTime from '@/utils/date.js'
export default {
  name: 'ArticeList',
  components: {
    ArticleItem
  },
  props: {
    cId: Number
  },

  data () {
    return {
      articlesList: [],
      // 频道ID
      channelId: this.cId,
      // 加载功能
      loading: false,
      finished: false,
      // 历史加载时间为上一次请求的返回值
      nextTimes: null,
      // 下拉刷新状态
      refreshing: false
    }
  },
  async  created () {
    this.getArticleList()
  },
  mounted () {
    // console.log(1)
    this.$bus.$on('refreshPage', () => {
      console.log(this)
      this.getArticleList()
    })
  },
  methods: {
    async getArticleList () {
      try {
        const res = await getArticleListAPI({
          channelId: this.channelId,
          timestamp: this.nextTimes
        })
        res.data.data.results.forEach(item => {
          item.pubdate = formatTime(item.pubdate)
        })
        // 关闭下拉刷新
        this.refreshing = false
        if (res.data.data.results.length === 0) {
          this.finished = true
        } else {
          this.nextTimes = res.data.data.pre_timestamp // 保存下一页数据的时间(做分页用)
          this.articlesList = [...this.articlesList, ...res.data.data.results]
          this.loading = false
        }
      } catch (error) {
        this.$Notify({ type: 'warning', message: '获取新闻数据列表失败' })
      }
    },
    // 上滑刷新
    onLoad () {
      if (this.articlesList.length > 0) { // 与:immediate-check="false"二选一即可
        console.log('加载功能实现')
        this.getArticleList()
      }
    },
    // 下拉刷新
    onRefresh () {
      this.nextTimes = null
      this.articlesList = []
      this.getArticleList()
    }

  },
  beforeDestroy () {
    this.$bus.$off('refreshPage')
  }

}
</script>
